/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package biz;

import da.RelationJpaController;
import da.exceptions.PreexistingEntityException;
import da.exceptions.RollbackFailureException;
import entities.Relation;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;
import javax.transaction.UserTransaction;

/**
 *
 * @author THOHCGC00177
 */
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class RelationProgess {

    @Resource
    private UserTransaction utx;
    @PersistenceUnit(unitName = "ProjectSem4PU")
    private EntityManagerFactory emf = null;
    private RelationJpaController jpa;

    public RelationJpaController getJpa() {
        if (jpa == null) {
            jpa = new RelationJpaController(utx, emf);
        }
        return jpa;
    }
    /**
     * 
     * Function create a Relation 
     * @param relation
     * @throws PreexistingEntityException
     * @throws RollbackFailureException
     * @throws Exception 
     */
    public void createRelation(Relation relation) throws PreexistingEntityException, RollbackFailureException, Exception {
        getJpa().create(relation);
    }
    /**
     * 
     * Function get list Relation by ID
     * @param id
     * @return 
     */
    public List<Relation> getListRelationById(int id) {
        TypedQuery<Relation> tq = emf.createEntityManager().createQuery("SELECT d FROM Relation d WHERE d.technicalId.id = :id", Relation.class);
        tq.setParameter("id", id);
        try {
            return tq.getResultList();
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * Function get a relation by ID
     * @param id
     * @return 
     */
    public Relation getRelationById(int id) {
        TypedQuery<Relation> tq = emf.createEntityManager().createQuery("SELECT r FROM Relation r WHERE r.id = :id", Relation.class);
        tq.setParameter("id", id);
        try {
            return tq.getSingleResult();
        } catch (Exception e) {
            return null;
        }
    }
}
